package de.bastian.hinterleitner;

import java.util.ArrayList;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import de.bastian.hinterleitner.adaptersviews.StandardAdapter;
import de.bastian.hinterleitner.database.DataHelper;
import de.bastian.hinterleitner.tools.Constants;
import de.bastian.hinterleitner.tools.DeleteTask;
import de.bastian.hinterleitner.tools.Entry;
import de.bastian.hinterleitner.tools.EntrySorter;
import de.bastian.hinterleitner.tools.WatchYourCashActivity;
import de.hijacksoft.wyc.R;

public class Search extends WatchYourCashActivity implements
		OnItemClickListener, OnItemLongClickListener, OnClickListener {

	private EditText searchField;
	private TextView sumText;
	private ListView result;
	private ImageButton delete;

	private StandardAdapter adapter = new StandardAdapter(this,
			new ArrayList<Entry>());

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		initGUI();
	}

	private void initGUI() {
		searchField = (EditText) findViewById(R.id.search_edittext_input);
		sumText = (TextView) findViewById(R.id.search_text_sum);
		result = (ListView) findViewById(R.id.search_text_result);
		delete = (ImageButton) findViewById(R.id.search_button_delete);

		delete.setEnabled(false);
		delete.setOnClickListener(this);

		result.setAdapter(adapter);
		result.setOnItemClickListener(this);
		result.setOnItemLongClickListener(this);

		searchField.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				refreshList();
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// nothing
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// nothing
			}

		});

		searchField.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					finish();
				}
			}
		});

		findViewById(R.id.search_view).setOnTouchListener(
				new OnTouchListener() {

					@Override
					public boolean onTouch(View v, MotionEvent event) {
						finish();
						return false;
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			refreshList();
			setResult(RESULT_OK);
		}
	}

	private void refreshList() {
		String searchString = searchField.getText().toString();
		DataHelper dh = DataHelper.getDataHelper(Search.this);
		ArrayList<Entry> list = dh.getAllEntriesContaining(searchString);
		updateSum(list);
		list = EntrySorter.getSingleton(this).sortBy(list, searchString);
		adapter.fatString = searchString;
		adapter.setItems(list);
		adapter.notifyDataSetChanged();
		if (list.size() > 0) {
			delete.setEnabled(true);
		} else {
			delete.setEnabled(false);
		}
	}
	
	private void updateSum(ArrayList<Entry> list){
		double plus = 0;
		double minus = 0;
		for(Entry e : list){
			if(e.getValue()>0){
				plus += e.getValue();
			}else{
				minus += e.getValue();
			}
		}
		double sum = plus+minus;
		String unit = getString(R.string.currency);
		sumText.setText(getString(R.string.total)+":\t"+
				roundToDecimals(2, sum)+unit+" (+"+roundToDecimals(2, plus)+unit+" -"+roundToDecimals(2, Math.abs(minus))+unit+")");
	}

	public void onItemClick(AdapterView<?> av, View view, int i, long l) {
		Intent intent = new Intent(this, NewEntry.class);
		intent.putExtra("itemId", "" + adapter.getItemId(i));
		startActivityForResult(intent, Constants.REQUEST_EDIT_ITEM);
	}

	public boolean onItemLongClick(AdapterView<?> av, View view, int i, long l) {
		final int id = i;
		question(
				getString(R.string.deletequestion).replace("$1",
						adapter.getItem(id).getName()),
				getString(R.string.yes), getString(R.string.no),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface di, int i) {
						DataHelper d = DataHelper.getDataHelper(Search.this);
						d.delete((int) adapter.getItemId(id));
						setResult(RESULT_OK);
						refreshList();
					}
				}, null);
		return true;
	}

	@Override
	public boolean hasOptionsMenu() {
		return false;
	}

	@Override
	public void onClick(View arg0) {
		question(getString(R.string.deleteall).replace("$1", adapter.getItems().size()+""),
				getString(R.string.yes),
				getString(R.string.no),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						new DeleteTask(Search.this, adapter.getItems()){
							@Override
							public void onFinish(boolean success) {
								refreshList();
							}
						}.execute();
					}
				},
				null);
	}

}
